//# default settings 
clear all
set more off
set scheme sj
capture log close

* define directories *
cd "YOUR WORKING DIRECTORY"
global PUTDIR "`c(pwd)'\tables and figures"

* load mata function *
include "comb_n_local.mata"

//# load and prepare data 
* load data set *
import delimited using "data/portfolio_allocation.csv", clear encoding(utf8)


//# loop over portfolio allocation data
local i = 1

foreach id of numlist 2/76 {
	import delimited using "data/portfolio_allocation.csv", clear rowrange(`id':`id') encoding(utf8)
	
	mata comb_n_local()
	compress
	
	if `i' == 1 {
		save "analysis_data.dta", replace
	}
	if `i' > 1 {
		append using "analysis_data.dta", force
		save "analysis_data.dta", replace
	}
	
	local ++i
}


//# run empirical models
* model 1 *
clogit outcome_qual equitability proportionality, group(id)
estat ic
est store model1
estimates save "$PUTDIR\model_1", replace

* model 2
clogit outcome_qual qual_prop, group(id)
estat ic
est store model2
estimates save "$PUTDIR/model_2", replace

* model 3
clogit outcome_qual equitability proportionality qual_prop coalition mayor_party, group(id)
estat ic
est store model3
estimates save "$PUTDIR/model_3", replace

//# store model results
esttab model1 model2 model3 using "$PUTDIR/table_results.rtf", replace label ///
	star(* 0.001) se(2) b(%9.2f) aic scalars(ll) ///
	mtitles("Model 1" "Model 2" "Model 3")

	

//# generate model estimates (MERs and predicted probabilities)
estimates use "$PUTDIR/model_3"
clogit	
estimates esample:

* estimate marginal effects at representative values (MERs)
est restore model3 
margins, dydx(equitability proportionality qual_prop) at(equitability = -0.3 proportionality = -0.15 coalition = 0 qual_prop = -0.1 mayor_party = 0)

mat res = r(table)
mat res = res'

preserve
clear 
svmat res

keep res1 res2
rename res1 AME
generate lower = AME-invnormal(0.975)*res2
generate upper = AME+invnormal(0.975)*res2
gen factor = ""
replace factor = "Quantitative equitability" in 1
replace factor = "Quantitative proportionality" in 2
replace factor = "Qualitative proportionality" in 3

export delimited "$PUTDIR/fig1_data.csv", replace
restore 

* estimate marginal effects at representative values (MERs)
margins, at(equitability =(-0.1 0.1) qual_prop =(-0.5(0.1)0.5) proportionality =(-0.5(0.1)0.5)  coalition = 0 mayor_party = 0) atmeans nose

mat res = r(table)
mat res = res'
mat res = res, r(at)

preserve
clear 
svmat res

rename res1 predprob
rename res2 quant_equitability  
rename res3 quant_proportionality
drop res5 
rename res4 qual_proportionality
keep if predprob != .

export delimited "$PUTDIR/fig2_data.csv", replace
restore
